const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { check, validationResult } = require('express-validator');
const { User } = require('../models/User');
const { Op } = require('sequelize');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// JWT密钥
const JWT_SECRET = 'your-jwt-secret';

// 获取WebSocket clients
let wss;
router.setWebSocketServer = function(websocketServer) {
    wss = websocketServer;
};

// 配置头像上传
const avatarStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        const dir = path.join(__dirname, '..', 'public', 'uploads', 'avatars');
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        cb(null, dir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, 'avatar-' + uniqueSuffix + path.extname(file.originalname));
    }
});

const avatarUpload = multer({
    storage: avatarStorage,
    limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
    },
    fileFilter: function (req, file, cb) {
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
            return cb(new Error('只允许上传图片文件！'));
        }
        cb(null, true);
    }
});

// 注册新用户
router.post('/register', [
    check('account', '账号长度必须在3-20个字符之间').isLength({ min: 3, max: 20 }),
    check('password', '密码至少需要6个字符').isLength({ min: 6 })
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { account, password } = req.body;

        // 检查账号是否已存在
        const existingUser = await User.findOne({
            where: { account }
        });

        if (existingUser) {
            return res.status(400).json({ msg: '账号已被使用' });
        }

        // 加密密码
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        // 创建新用户
        const user = await User.create({
            account,
            password: hashedPassword
        });

        // 创建JWT
        const payload = {
            user: {
                id: user.id
            }
        };

        jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' }, (err, token) => {
            if (err) throw err;
            res.json({ token });
        });
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

// 用户登录
router.post('/login', [
    check('account', '请输入账号').exists(),
    check('password', '请输入密码').exists()
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { account, password } = req.body;

        // 检查用户是否存在
        const user = await User.findOne({ where: { account } });
        if (!user) {
            return res.status(400).json({ msg: '账号不存在' });
        }

        // 验证密码
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ msg: '密码错误' });
        }

        // 创建JWT
        const payload = {
            user: {
                id: user.id
            }
        };

        jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' }, (err, token) => {
            if (err) throw err;
            res.json({ token });
        });
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

// 更新用户头像
router.post('/avatar', avatarUpload.single('avatar'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ msg: '没有文件被上传' });
        }

        const token = req.header('x-auth-token');
        const decoded = jwt.verify(token, JWT_SECRET);
        const userId = decoded.user.id;

        const user = await User.findByPk(userId);
        if (!user) {
            return res.status(404).json({ msg: '用户不存在' });
        }

        // 如果有旧头像且不是默认头像，则删除
        if (user.avatar && user.avatar !== '/uploads/avatars/default.png') {
            const oldAvatarPath = path.join(__dirname, '..', 'public', user.avatar);
            if (fs.existsSync(oldAvatarPath)) {
                fs.unlinkSync(oldAvatarPath);
            }
        }

        // 更新用户头像
        const avatarUrl = '/uploads/avatars/' + req.file.filename;
        await user.update({ avatar: avatarUrl });

        // 获取所有在线的好友并通知他们头像更新
        if (wss) {
            const friends = await user.getFriends({
                through: {
                    where: {
                        status: 'accepted'
                    }
                }
            });

            const clients = wss.clients;
            friends.forEach(friend => {
                for (const client of clients) {
                    if (client.userId === friend.id) {
                        client.send(JSON.stringify({
                            type: 'avatarUpdate',
                            userId: userId,
                            avatar: avatarUrl
                        }));
                    }
                }
            });
        }

        res.json({
            msg: '头像更新成功',
            avatar: avatarUrl
        });
    } catch (err) {
        console.error('头像上传失败:', err);
        res.status(500).json({ msg: '头像上传失败' });
    }
});

// 获取用户信息
router.get('/me', async (req, res) => {
    try {
        const token = req.header('x-auth-token');
        const decoded = jwt.verify(token, JWT_SECRET);
        const userId = decoded.user.id;

        const user = await User.findByPk(userId, {
            attributes: ['id', 'account', 'avatar', 'createdAt']
        });

        if (!user) {
            return res.status(404).json({ msg: '用户不存在' });
        }

        res.json(user);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

module.exports = router; 